package com.ryan.chat.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.ryan.chat.entity.ChatInfoDTO;
import com.ryan.chat.entity.ResponseDTO;
import com.ryan.chat.service.ChatAiService;
import com.ryan.chat.util.RequestUtil;
import com.zhipu.oapi.ClientV4;
import com.zhipu.oapi.Constants;
import com.zhipu.oapi.service.v4.model.ChatCompletionRequest;
import com.zhipu.oapi.service.v4.model.ChatMessage;
import com.zhipu.oapi.service.v4.model.ChatMessageRole;
import com.zhipu.oapi.service.v4.model.ModelApiResponse;

import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author 308039
 * @version 1.0.0
 * @type ChatAiServiceImpl.java
 * @description
 * @date 2024/10/22 16:51
 */
@Service
@Slf4j
public class ChatAiServiceImpl implements ChatAiService {

    private static final Pattern PATTERN = Pattern.compile("\"content\":\"((?:[^\"\\\\]|\\\\.)*?)\"");

    private static final String API_KEY = "f54a01a7d4d12ba541b3a60ccc0d690c.kfvmIViysfbDbcAE";
    private static final ClientV4 client = new ClientV4.Builder(API_KEY).build();

    // 请自定义自己的业务id
    private static final String requestIdTemplate = "zrh-%d";

    public static void main1(String[] args) {
        // String question = "作为一名营销专家，请为智谱开放平台创作一个吸引人的slogan";
        String question = "使用java打印 helloworld";
        List<ChatMessage> messages = new ArrayList<>();
        ChatMessage chatMessage = new ChatMessage(ChatMessageRole.USER.value(), question);
        messages.add(chatMessage);
        String requestId = String.format(requestIdTemplate, System.currentTimeMillis());

        ChatCompletionRequest chatCompletionRequest =
            ChatCompletionRequest.builder().model(Constants.ModelChatGLM4).stream(Boolean.FALSE)
                .invokeMethod(Constants.invokeMethodAsync).messages(messages).requestId(requestId).build();
        ModelApiResponse invokeModelApiResp = client.invokeModelApi(chatCompletionRequest);
        System.out.println("model output:" + JSON.toJSONString(invokeModelApiResp));

    }

    @Override
    public String chatHuluAi(String prompt) {

        ChatAiService chatAiService = new ChatAiServiceImpl();
        ChatInfoDTO chatInfoDTO = chatAiService.sendPrompt(prompt);

        String message = chatAiService.startChat(chatInfoDTO.getChatId());

        System.out.println("message = " + message);
        return message;
    }

    @Override
    public ChatInfoDTO sendPrompt(String prompt) {
        Map<String, Object> formMap = new HashMap<>(2);
        formMap.put("sessionId", "c9a719b7a8c4451aaca8e9830d4b8802");
        formMap.put("prompt", prompt);
        Map<String, String> headers = getHeadersMap();
        String responseBody = RequestUtil.requestSend(Method.POST,
            "https://www.huluai.net/sqx_fast/app/user-session/chat/c9a719b7a8c4451aaca8e9830d4b8802", headers, formMap,
            null);

        ResponseDTO chatInfoDTO = JSONUtil.toBean(responseBody, ResponseDTO.class);
        return JSONUtil.toBean((JSONObject)chatInfoDTO.getData(), ChatInfoDTO.class);
    }

    @Override
    public String startChat(Integer chatId) {

        Map<String, String> headers = getHeadersMap();
        String body = "{\"sessionId\":\"c9a719b7a8c4451aaca8e9830d4b8802\",\"chatId\":" + chatId + "}";
        String responseBody = RequestUtil.requestSend(Method.POST,
            "https://www.huluai.net/sqx_fast/app/user-session/chat/c9a719b7a8c4451aaca8e9830d4b8802/" + chatId, headers,
            null, body);

        // ResponseDTO responseDTO = JSONUtil.toBean(responseBody, ResponseDTO.class);
        //
        // JSONUtil.toBean((JSONObject)responseDTO.getData(), ChatSessionInfoDTO.class);

        List<String> contents = extractContents(responseBody);
        StringBuilder stringBuilder = new StringBuilder();
        for (String content : contents) {
            stringBuilder.append(content);
        }

        return stringBuilder.toString();
    }

    public static List<String> extractContents(String responseBody) {
        List<String> contents = new ArrayList<>();
        Matcher matcher = PATTERN.matcher(responseBody);

        while (matcher.find()) {
            contents.add(matcher.group(1));
        }

        return contents;
    }

    @Override
    public String queryAnswer() {
        return "";
    }

    @Override
    public String deleteChatHistory() {
        Map<String, String> headers = getHeadersMap();

        return RequestUtil.requestSend(Method.DELETE,
            "https://www.huluai.net/sqx_fast/app/user-session/clearSession/c9a719b7a8c4451aaca8e9830d4b8802?sessionId=c9a719b7a8c4451aaca8e9830d4b8802",
            headers, null, null);
    }

    /**
     * 获取请求头
     * 
     * @return
     */
    private static @NotNull Map<String, String> getHeadersMap() {
        Map<String, String> headers = new HashMap<>(0);

        headers.put("Token",
            "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI4NTAyNiIsImlhdCI6MTcyOTIzMjgzMiwiZXhwIjoxNzI5ODM3NjMyfQ.8hSXMFhar991Npz18bAQbTkqEgpC9udXoIwJW5IVw1043OhlzdiBRuP5qfl4sbWCWvsmtkmbHWsJoPnrEvd5RA");
        headers.put("Accept", "*/*");
        headers.put("Accept-Encoding", "gzip, deflate, br");
        headers.put("Connection", "keep-alive");
        headers.put("content-type", "multipart/form-data; boundary=---011000010111000001101001");
        headers.put("User-Agent",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36");

        return headers;
    }

}
